package vikaa.tools;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;

public class InternalStoragePrivate {
	/**
	 * Writes content to internal storage making the content private to 
	 * the application. The method can be easily changed to take the MODE 
	 * as argument and let the caller dictate the visibility: 
	 * MODE_PRIVATE, MODE_WORLD_WRITEABLE, MODE_WORLD_READABLE, etc.
	 * 
	 * @param filename - the name of the file to create
	 * @param content - the content to write
	 * @return 
	 */
	public static void writeInternalStoragePrivate(
	        String filename, byte[] content,Context context) {
	    try {
	        
	        FileOutputStream fos = 
	        		context.openFileOutput(filename, Context.MODE_PRIVATE);
	        fos.write(content);
	        fos.close();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}
	/**
	 * Reads a file from internal storage
	 * @param filename the file to read from
	 * @return the file content
	 */
	public static byte[] readInternalStoragePrivate(String filename,Context context) {
	    int len = 1024;
	    byte[] buffer = new byte[len];
	    try {
	        FileInputStream fis = context.openFileInput(filename);
	        ByteArrayOutputStream baos = new ByteArrayOutputStream();
	        int nrb = fis.read(buffer, 0, len); // read up to len bytes
	        while (nrb != -1) {
	            baos.write(buffer, 0, nrb);
	            nrb = fis.read(buffer, 0, len);
	        }
	        buffer = baos.toByteArray();
	        fis.close();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return buffer;
	}
	/**
	 * Delete internal private file 
	 * @param filename - the filename to delete
	 * @return 
	 */
	public static void deleteInternalStoragePrivate(String filename,Context context) {
	    File file = context.getFileStreamPath(filename);
	    if (file != null) {
	        file.delete();
	    }
	}
}
